# -*- coding: utf-8 -*-
'''Simple data loader module.

Loads data files from the "data" directory shipped with a game.

Enhancing this to handle caching etc. is left as an exercise for the reader.
'''

import os
from pygame.constants import *
import pygame.image

#data_py = os.path.abspath(os.path.dirname(__file__))
#data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
data_dir = 'data'
image_dir = os.path.join(data_dir, 'images')
tile_dir = os.path.join(image_dir, 'tiles')
anim_dir = os.path.join(image_dir, 'animation')

misc_dir = os.path.join(data_dir, 'misc')

def filepath(filename):
    '''Determine the path to a file in the data directory.
    '''
    return os.path.join(data_dir, filename)

def load(filename, mode='rb'):
    '''Open a file in the data directory.

    "mode" is passed as the second arg to open().
    '''
    return open(os.path.join(data_dir, filename), mode)

def load_image(filename, colorkey = None, use_own_dir=False):
    """Load an image with the supplied colorkey (optional).
    If colorkey is -1, use the color of the first pixel of
    the image.
    If use_own_dir is set to true, load consider filename
    an absolute path, otherwise use ./images. This is a hack.
    Returns a surface, and a rect of the same size"""
    if not use_own_dir:
        path = os.path.join(image_dir, filename)
    else: 
        path = filename
    try:
        image = pygame.image.load(path)
    except pygame.error, message:
        print "Could not load image", filename
        raise #SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
